import tkinter as tk
from tkinter import messagebox
from tkinterdnd2 import DND_FILES, TkinterDnD

import os
import subprocess


class VideoToGifConverter:
    def __init__(self):
        # 获取临时解压目录也就是真实目录，不能使用.来获取当前路径，其获取的是运行exe文件的路径
        self.run_dir = os.path.dirname(__file__)
        self.root = TkinterDnD.Tk()
        self.root.iconbitmap(f'{self.run_dir}/19n.ico')
        self.root.title("视频转 GIF 工具")
        self.root.geometry("400x200")

        self.label = tk.Label(self.root, text="将视频拖放到此处")
        self.label.pack(pady=20)

        # Bind the drop event  
        self.root.drop_target_register(DND_FILES)
        self.root.dnd_bind('<<Drop>>', self.handle_drop)

        self.video_path = None

    def handle_drop(self, event):
        # Get the video path from the drop event  
        files = self.root.tk.splitlist(event.data)
        if files:
            self.video_path = files[0]
            self.convert_video()

    def convert_video(self):
        if self.video_path and os.path.isfile(self.video_path):
            output_path = os.path.join(os.path.dirname(self.video_path),
                                       os.path.splitext(os.path.basename(self.video_path))[0] + '.gif')
            try:
                cmd = f'{self.run_dir}/ffmpeg.exe -i {self.video_path} -vf "split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" {output_path} -y'
                # 执行命令不弹出窗口
                subprocess.Popen(cmd, creationflags=subprocess.CREATE_NO_WINDOW, shell=True)
                messagebox.showinfo("转换完成", f"视频已成功转换为 GIF 并保存至：\n{output_path}")
            except Exception as e:
                messagebox.showerror("错误", f"转换过程中出现错误：\n{str(e)}")
        else:
            messagebox.showwarning("警告", "请拖放有效的视频文件")

    def on_close(self):
        self.root.destroy()


if __name__ == "__main__":
    converter = VideoToGifConverter()
    converter.root.mainloop()
